<template>
  <div class="app-container">
    <el-form  class="query-wrapper" :model="queryParams" inline>
      <el-form-item prop="brand">
        <el-input v-model="queryParams.brand" style="width: 180px" placeholder="Brand"/>
      </el-form-item>
      <el-form-item prop="name">
        `<el-input v-model="queryParams.name" style="width: 180px" placeholder="Model"/>
       </el-form-item>
      <el-form-item>   
        
        <el-button type="primary" icon="search" @click="search">{{
          $t("ship.button.search")
        }}</el-button>
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
        &nbsp;&nbsp;
        <el-button type="primary" plain icon="Plus" @click="addClickEvent" v-hasPermi="['declared:edit']" >

          {{ $t("ship.button.plus") }}
        </el-button>
        <el-button type="primary" icon="upload" @click="uploadFileForm"  v-hasPermi="['declared:edit']">Import</el-button>
      <!-- <el-button type="primary" onclick="this.nextSibling.click()">Import</el-button>
        <input
          id="upload-spec-file"
          type="file"
          accept=".xls,.xlsx"
          v-show="false"
          @change="uploadFile($event)"
        />   -->
      </el-form-item>
    </el-form>
  </div>

  <el-table
    class="daf-table"
    stripe
    :data="listData"
    @sort-change="handleSortChange"
    show-overflow-tooltip    
    :header-cell-style ="{textAlign:'center'}" 
  > 
    <el-table-column prop="brand" label="Brand" width="100"/>
    <el-table-column prop="name" label="Model" width="180" /> 
    <el-table-column prop="cargoType" label="Cargo Type" width="260" /> 
    <el-table-column prop="description" label="Description(详细描述)" width="150"  align="center"/> 
    <el-table-column prop="fuelType" label="Fuel Type" width="100" /> 
    <el-table-column prop="declareLength" label="Length(m)" />  
    <el-table-column prop="declareWidth" label="width(m)" /> 
    <el-table-column prop="declareHeight" label="Height(m)" width="120" /> 
    <el-table-column prop="weight" label="Weight(kg)" width="90" />
    <el-table-column prop="createBy" label="Created By" width="100" /> 
    <!-- <el-table-column prop="envType" label="Fuel Type" />  -->
     <el-table-column label="Operation" v-hasPermi="['declared:edit']" width="120" fixed="right">
      <template #default="scope">
        <span class="btn-primary"  @click="editClickEvent(scope.row)">{{
          $t("ship.button.edit")
        }}</span
        >&nbsp;&nbsp;
        <span class="btn-primary" @click="removeClickEvent(scope.row.id)">{{
          $t("ship.button.remove")
        }}</span>
      </template>
    </el-table-column>
  </el-table>

  <pagination
    v-show="total > 0"
    :total="total"
    :page="queryParams.pageNum"
    :limit="queryParams.pageSize"
    @pagination="pageQuery"
    style="float: right"
  />

  <el-dialog
    :width="1000"
    destroy-on-close
    draggable
    :title="dialogTitle"
    v-model="dialogFormVisible"
  >
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="Brand" label-width="120px" prop="brand" required>
            <el-input v-model="formParam.brand" placeholder="Please input"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="Model" label-width="120px" prop="name" required>
            <el-input v-model="formParam.name" placeholder="Please input"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="Cargo Type" label-width="120px" prop="cargoType">
            <el-select v-model="formParam.cargoType" filterable clearable allow-create style="width: 100%;">  
              <el-option v-for="item in cargo_type" :key="item.label" :label="item.label" :value="item.label" />
            </el-select> 
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Description" label-width="120px" prop="description">
             <el-input type="textare" v-model="formParam.description" placeholder="Please input" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="FUEL TYPE" label-width="120px" prop="fuelType">
            <el-select v-model="formParam.fuelType" filterable clearable allow-create style="width: 100%;"> 
              <el-option v-for="item in fuel_type" :key="item.label" :label="item.label" :value="item.label" placeholder="Please input" />
            </el-select> 
          </el-form-item>
        </el-col> 
        <el-col :span="12">
          <el-form-item label="Length(m)" label-width="120px" prop="declareLength" required>
            <el-input-number v-model="formParam.declareLength" :precision="3" :min="0" :max="100" placeholder="Please input" /> 
          </el-form-item>
        </el-col>
      </el-row>  

      <el-row> 
        <el-col :span="12">
          <el-form-item label="Width(m)" label-width="120px" prop="declareWidth" required>
            <el-input-number v-model="formParam.declareWidth" :precision="3" :min="0" :max="100" placeholder="Please input" />
          </el-form-item>
        </el-col> 
        <el-col :span="12">
          <el-form-item label="Height(m)" label-width="120px" prop="declareHeight" required>
            <el-input-number v-model="formParam.declareHeight" :precision="3" :min="0" :max="100" placeholder="Please input" />
          </el-form-item>
        </el-col> 
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
        }}</el-button> 
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
        }}</el-button>
      </span>
    </template>
  </el-dialog> 
  <FileUpload ref="fileUploadRef" :url="downTemplateUrl" :templateFile="templateFile" :isAlink="false" :queryParams="queryParams" :uploadFileUrl="uploadFileUrl" :fileType="fileType" @update:modelValue="updateFileUpload"  />
</template>
<script lang="ts" setup name="declaredMeasured">
import { ref, onMounted, reactive } from "vue"; 
import {ElMessage} from 'element-plus'
import service from "@/utils/request"; 

import { ElNotification, ElMessageBox } from "element-plus"; 
const { proxy } = getCurrentInstance();
const custForm = ref(null);
const dialogTitle = ref("");
const initForm = {
  id: null,
  brand: null,
  name: null,
  fuelType: null,
  cargoType: null,
  declareLength: null,
  declareWidth: null,
  declareHeight: null ,
};
const formParam = reactive(Object.assign({}, initForm));

const total = ref(0);

const rules = ref({
  name: [{ required: true, message: "Model is required" }],
  brand: [{ required: true, message: "Brand is required" }], 
  declareLength:  [{ required: true, message: "Length(m) is required" }], 
  declareWidth:  [{ required: true, message: "Width(m) is required" }], 
});
const templateFile=ref('vehicleModel.xlsx')
const fuelTypes = ["Non-EV", "BEV", "HEV", "PHEV", "EREV", "FCV", "EV", "OTHER"];
const types = ["passenger car"];
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  name: null,
  brand: null,
  orderByColumn: undefined,
  isAsc: undefined,
});
 
const listData = ref([]);
const refreshTable = async () => {
  let result = await service.get("/shipping/vehicleModel/getTable", {
    params: queryParams,
  });
  listData.value = result.data;
  total.value = result.total;
};
const resetQuery = (data) => {
    Object.assign(queryParams, data)
    refreshTable()
}
const dialogFormVisible = ref(false);

const editClickEvent = (row: any) => {
  dialogTitle.value = "Update Declared Dimension";
  dialogFormVisible.value = true;
  isAdd = false;
  Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
};

let isAdd = false;

const addClickEvent = () => {
  dialogTitle.value = "Add Declared Dimension";
  isAdd = true;
  dialogFormVisible.value = true;
  Object.assign(formParam, initForm);
};

const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => { 
 
  // @ts-ignore
  custForm.value.validate(async (valid) => {
    if (!valid) { 
      // @ts-ignore
      ElNotification.warning({
        title: "Prompt information",
        message: "verification not success！",
        position: "bottom-right",
      });
      return;
    }

    if(formParam.cargoType !='Parts' && (formParam.fuelType == null|| formParam.fuelType=='')){ 
       ElMessage.warning(  "Fuel Type is required！" );
      return;
    }
 
    await service[isAdd ? "post" : "put"]("shipping/vehicleModel", formParam);
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right",
    });
    dialogFormVisible.value = false;
    refreshTable();
  });
};

const pageQuery = async (e) => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const search = () => {
  refreshTable();
};

const sleep = (ms) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};

const removeClickEvent = (id) => {
  ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    await service.delete(`shipping/vehicleModel/${id}`);

    refreshTable();
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "Delete successfully!",
      position: "bottom-right",
    });
  });
};

const uploadFile = async (event) => {
  if (event.target == null || event.target.files[0] == null) {
    return;
  }
  const formData = new FormData();
  formData.append("file", event.target.files[0]);
  await service["post"]("shipping/vehicleModel/uploadFile", formData);
};

// 导入功能
const uploadFileUrl = "/shipping/vehicleModel/uploadFile"
const downTemplateUrl=ref('shipping/vehicleModel/download/template')
const fileType=ref(['.xlsx','.xls'])
const fileUploadRef=ref(null)
const uploadFileForm=()=>{
  proxy.$refs["fileUploadRef"].dialogUploadFileForm()
}
const updateFileUpload= (data: any) => {
  refreshTable();
};

let cargo_type = reactive([])
let fuel_type = reactive([])
onMounted(async () => {
  refreshTable();

  const res = await proxy.useDict("cargo_type","fuel_type");
  cargo_type = res.cargo_type
  fuel_type = res.fuel_type
});
</script>
<style lang="scss" scoped>
.el-table__expand-column .cell {
  display: none;
}
::v-deep.el-table td.el-table__cell div{
    text-align: center;
}
.c-expand {
  color: #888;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  cursor: pointer;
  width: 100%;
  height: 100%;
}
.c-expand i {
  font-size: 16px;
}
.c-expand i.expand {
  font-size: 16px;
  transform: rotate(90deg);
  transition: all 0.25s;
}
</style>
